package com.jacobson.core.base

import android.app.Application
import android.content.Context
import com.jacobson.core.App
import com.jacobson.core.base.delegate.AppDelegate
import com.jacobson.core.base.delegate.AppLifecycle
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.utils.Preconditions

/**
 * ================================================
 *
 * @author Wucz on 2018/7/16 9:17
 * ================================================
 */
open class BaseApplication(
        private var mAppDelegate: AppLifecycle? = null
) : Application(), App {

    companion object{
        private var instance:Application? = null

        fun instance()= instance!!
    }

    /**
     * 这里会在[Application.onCreate]之前被调用,可以做一些较早的初始化
     * 常用于 MultiDex 以及插件化框架的初始化
     */
    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        if (mAppDelegate == null) {
            mAppDelegate = AppDelegate(base)
        }
        mAppDelegate!!.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        mAppDelegate!!.onCreate(this)
    }

    override fun onTerminate() {
        super.onTerminate()
        mAppDelegate!!.onTerminate(this)
    }

    override fun provideAppComponent(): AppComponent {
        Preconditions.checkNonNull(mAppDelegate, "${AppDelegate::class.java.simpleName} cannot be null!")
        Preconditions.checkState(mAppDelegate is App, "${AppDelegate::class.java.simpleName} must be implements ${App::class.java.simpleName}")
        return (mAppDelegate as App).provideAppComponent()
    }
}